package com.memory.wechat.domain.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.memory.wechat.domain.util.wx.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class WxRequestUtil {
    private static final String APP_ID = "wx3be7708836dff81e";
    private static final String APP_SECRET = "fc4b7b421247ced597439e159e014b63";
    private static Menu getMenu() throws Exception{
        CommonButton button = new CommonButton();
        button.setKey("zcjj");
        button.setName("众存简介");
        button.setType("click");

        CommonButton button2 = new CommonButton();
        button2.setKey("cpjj");
        button2.setName("产品简介");
        button2.setType("click");


        CommonButton button3 = new CommonButton();
        button3.setKey("ipfs");
        button3.setName("IPFS介绍");
        button3.setType("click");

        CommonButton button4 = new CommonButton();
        button4.setKey("crust");
        button4.setName("crust项目简介");
        button4.setType("click");

        ComplexButton cb1 = new ComplexButton();
        cb1.setName("项目介绍");
        cb1.setSub_button(new Button[]{button,button2,button3,button4});

        ViewButton viewButton = new ViewButton();
        viewButton.setName("个人中心");
        viewButton.setType("view");
        String url = "http://2wok.com/personal/center";
        url = URLEncoder.encode(url,"UTF-8");
        String api = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APP_ID+"&redirect_uri="+url+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        viewButton.setUrl(api);
        Menu menu = new Menu();
        menu.setButton(new Button[]{cb1,viewButton});

        return menu;
    }

    public static String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ APP_ID + "&secret=" +APP_SECRET;
        String accessToken = null;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET");      //必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
            http.connect();
            InputStream is =http.getInputStream();
            int size =is.available();
            byte[] jsonBytes =new byte[size];
            is.read(jsonBytes);
            String message=new String(jsonBytes,"UTF-8");

            System.out.println(">>>>获取accessToken响应："+message);
            JSONObject accessJson = JSON.parseObject(message);
            accessToken = accessJson.getString("access_token");
            System.out.println(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    public static WxUser getUserInfo(String openid) throws Exception{
        String accessToken = getAccessToken();
        System.out.println(">>>"+accessToken);
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET");      //必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
            http.connect();
            InputStream is =http.getInputStream();
            int size =is.available();
            byte[] jsonBytes =new byte[size];
            is.read(jsonBytes);
            String message=new String(jsonBytes,"UTF-8");
            JSONObject msgObj = JSON.parseObject(message);
            return WxUser.builder()
                    .openId(msgObj.getString("openid"))
                    .nickName(msgObj.getString("nickname"))
                    .sex(msgObj.getInteger("sex"))
                    .city(msgObj.getString("city"))
                    .province(msgObj.getString("province"))
                    .country(msgObj.getString("country"))
                    .build();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getOpenIdByCode(String code) throws Exception {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APP_ID+"&secret="+APP_SECRET+"&code="+code+"&grant_type=authorization_code";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET");      //必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
            http.connect();
            InputStream is =http.getInputStream();
            int size =is.available();
            byte[] jsonBytes =new byte[size];
            is.read(jsonBytes);
            String message=new String(jsonBytes,"UTF-8");
            JSONObject accessJson = JSON.parseObject(message);
            String openid = accessJson.getString("openid");
            return openid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void createMenu(Menu menu) {
        String jsonMenu=JSON.toJSONString(menu);
        String accessToken = getAccessToken();
        String path="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+accessToken;
        try {
            URL url=new URL(path);
            HttpURLConnection http = (HttpURLConnection)url.openConnection();
            http.setDoOutput(true);
            http.setDoInput(true);
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.connect();
            OutputStream os = http.getOutputStream();
            os.write(jsonMenu.getBytes("UTF-8"));
            os.close();

            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] bt = new byte[size];
            is.read(bt);
            String message=new String(bt,"UTF-8");
            System.out.println(">>>>>>>>>>>创建菜单响应结果："+message);
        }catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) throws Exception{
        /*Menu menu = getMenu();
        createMenu(menu);*/
        /*String openid = "ocj3U6G1nzqdfDS-9GWn18N4rujQ";
        WxUser user = getUserInfo(openid);
        System.out.println(">>>"+JSON.toJSONString(user));*/
        getOpenIdByCode("123123");

    }


}
